#!/usr/bin/env python3
"""
手动添加商品到数据库（无需Shopify API连接）
"""

import os
import sys
import logging
from datetime import datetime

# 添加当前目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 导入数据库相关模块
from database.connection import async_session
from database.models import Product
import asyncio

def get_product_info():
    """获取用户输入的商品信息"""
    print("\n请输入新商品信息（直接按回车使用默认值）")
    
    # 获取用户在Shopify上传的商品信息
    name = input("商品名称: ") or "新商品"
    description = input("商品描述: ") or "暂无描述"
    
    # 获取价格（默认99.99）
    try:
        price_input = input("商品价格: ")
        price = float(price_input) if price_input else 99.99
    except ValueError:
        logger.warning("价格输入无效，使用默认价格")
        price = 99.99
    
    # 获取库存（默认10）
    try:
        stock_input = input("库存数量: ")
        stock_quantity = int(stock_input) if stock_input else 10
    except ValueError:
        logger.warning("库存输入无效，使用默认库存")
        stock_quantity = 10
    
    # 获取Shopify产品ID
    shopify_id = input("Shopify产品ID (可选): ") or f"manual_{int(datetime.utcnow().timestamp())}"
    
    # 获取分类ID（默认1）
    try:
        category_input = input("分类ID (默认1): ")
        category_id = int(category_input) if category_input else 1
    except ValueError:
        logger.warning("分类ID输入无效，使用默认分类")
        category_id = 1
    
    return {
        'name': name,
        'description': description,
        'price': price,
        'stock_quantity': stock_quantity,
        'shopify_product_id': shopify_id,
        'category_id': category_id,
        'is_active': True
    }

async def add_product_to_database(product_info):
    """将商品添加到数据库"""
    async with async_session() as session:
        try:
            # 检查是否已存在同名商品
            from sqlmodel import select
            result = await session.execute(
                select(Product).where(Product.name == product_info['name'])
            )
            existing_product = result.scalar_one_or_none()
            
            if existing_product:
                logger.info(f"商品 '{product_info['name']}' 已存在，将更新信息")
                # 更新现有产品
                existing_product.name = product_info['name']
                existing_product.description = product_info['description'][:255]
                existing_product.price = product_info['price']
                existing_product.stock_quantity = product_info['stock_quantity']
                existing_product.category_id = product_info['category_id']
                existing_product.is_active = product_info['is_active']
                existing_product.shopify_product_id = product_info['shopify_product_id']
                existing_product.updated_at = datetime.utcnow()
                
                await session.commit()
                logger.info(f"商品更新成功！数据库ID: {existing_product.id}")
                return existing_product.id
            else:
                # 创建新产品
                logger.info(f"创建新商品: {product_info['name']}")
                new_product = Product(
                    name=product_info['name'],
                    description=product_info['description'][:255],
                    price=product_info['price'],
                    category_id=product_info['category_id'],
                    stock_quantity=product_info['stock_quantity'],
                    is_active=product_info['is_active'],
                    shopify_product_id=product_info['shopify_product_id'],
                    created_at=datetime.utcnow(),
                    updated_at=datetime.utcnow()
                )
                
                session.add(new_product)
                await session.commit()
                await session.refresh(new_product)
                logger.info(f"商品创建成功！数据库ID: {new_product.id}")
                return new_product.id
                
        except Exception as e:
            logger.error(f"添加商品到数据库失败: {e}")
            await session.rollback()
            import traceback
            traceback.print_exc()
            return None
        finally:
            await session.close()

async def main():
    """主函数"""
    logger.info("=== 手动商品添加工具 ===")
    logger.info("此工具可直接添加商品到数据库，无需Shopify API连接")
    
    while True:
        # 获取商品信息
        product_info = get_product_info()
        
        # 显示确认信息
        print("\n商品信息确认:")
        print(f"  名称: {product_info['name']}")
        print(f"  描述: {product_info['description']}")
        print(f"  价格: {product_info['price']}")
        print(f"  库存: {product_info['stock_quantity']}")
        print(f"  分类ID: {product_info['category_id']}")
        print(f"  Shopify ID: {product_info['shopify_product_id']}")
        
        confirm = input("\n确认添加这个商品吗？(y/n): ")
        if confirm.lower() != 'y':
            print("取消添加")
            continue
        
        # 添加到数据库
        product_id = await add_product_to_database(product_info)
        
        if product_id:
            print(f"\n✓ 商品添加成功！")
            print(f"✓ 数据库ID: {product_id}")
            print("✓ 请刷新后端管理页面查看新商品")
        else:
            print("\n✗ 商品添加失败")
        
        # 询问是否继续
        again = input("\n是否继续添加其他商品？(y/n): ")
        if again.lower() != 'y':
            break
    
    print("\n感谢使用手动商品添加工具！")

if __name__ == "__main__":
    asyncio.run(main())